import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import CourseCard from '../components/CourseCard';
import portfolioApi from '../utils/database';

const Courses = () => {
  const navigate = useNavigate();
  const [courses, setCourses] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // 加载所有课程
  const loadCourses = async () => {
    try {
      setLoading(true);
      setError(null);
      
      // 初始化 API 连接
      await portfolioApi.init();
      
      // 获取所有课程
      const coursesData = await portfolioApi.getAllCourses();
      setCourses(coursesData);
    } catch (err) {
      console.error('加载课程失败:', err);
      setError(err.message || '加载课程失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadCourses();
  }, []);

  // 查看课程作品
  const handleViewWorks = (course) => {
    navigate(`/works?courseId=${course.id}&courseName=${encodeURIComponent(course.name)}`);
  };

  if (loading) {
    return (
      <div className="mt-6">
        <div className="text-center py-12">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-4 text-gray-500 dark:text-gray-400">加载课程中...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="mt-6">
        <div className="text-center py-12 bg-red-50 dark:bg-red-900/20 rounded-lg">
          <p className="text-red-600 dark:text-red-400">{error}</p>
          <button 
            onClick={loadCourses} 
            className="mt-4 px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700 transition-colors"
          >
            重新加载
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="mt-6">
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6">
        <h2 className="text-2xl font-semibold">
          课程列表
          <span className="text-lg text-gray-500 dark:text-gray-400 ml-2">
            ({courses.length})
          </span>
        </h2>
      </div>
      
      {courses.length === 0 ? (
        <div className="text-center py-12 bg-gray-50 dark:bg-gray-800 rounded-lg">
          <p className="text-gray-500 dark:text-gray-400">
            暂无课程，请联系管理员添加
          </p>
        </div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
          {courses.map(course => (
            <CourseCard 
              key={course.id} 
              course={course} 
              onViewWorks={handleViewWorks}
            />
          ))}
        </div>
      )}
    </div>
  );
};

export default Courses;